package com.loong.order.handler;

import com.google.common.collect.Lists;
import com.loong.common.enumerate.ResultCode;
import com.loong.common.exception.GlobalException;
import com.loong.common.redis.RedisTools;
import com.loong.common.rest.rpc.RPCResponse;
import com.loong.common.utils.TransformUtils;
import com.loong.data.dto.GoodsSpecificationDTOResult;
import com.loong.data.service.IGoodsSpecificationService;
import com.loong.global.constant.RedisKey;
import com.loong.order.business.OrderItemBusiness;
import com.loong.order.common.forehead.param.OrderItemForeheadParam;
import com.loong.order.common.forehead.result.OrderItemResult;
import com.loong.order.model.OrderItem;
import com.loong.shop.dto.GoodsSkuDTOResultInShop;
import com.loong.shop.service.IGoodsSkuService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Component;


import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description: 订单详情服务
 * @Author: hzp
 * @Date: 2020-12-31 9:33
 */
@Slf4j
@Component
public class OrderItemHandler {
    @Resource
    private OrderItemBusiness orderItemBusiness;

    @DubboReference(timeout = 3000, retries = 1)
    private IGoodsSpecificationService iGoodsSpecificationService;

    @DubboReference(timeout = 3000, retries = 1)
    private IGoodsSkuService iGoodsSkuService;
    public Boolean checkPrice(List<OrderItemForeheadParam> orderItemList){
        List<Long> skuIdList = Lists.newArrayList();
        Map<Long, BigDecimal> orderSkuMap = new HashMap();
        Map<Long, BigDecimal> skuMap = new HashMap();
        orderItemList.forEach(orderItem -> {
            skuIdList.add(orderItem.getGoodsSkuId());
            orderSkuMap.put(orderItem.getGoodsSkuId(),orderItem.getPrice().stripTrailingZeros());
        });
        RPCResponse<List<GoodsSkuDTOResultInShop>> goodsSkuListInRpc = iGoodsSkuService.findGoodsSkuListInSkuId(skuIdList);
        List<GoodsSkuDTOResultInShop> rpcList = goodsSkuListInRpc.getData();
        rpcList.forEach(sku-> skuMap.put(sku.getId(),sku.getCurrentPrice().stripTrailingZeros()));
        log.debug("==============orderSkuMap :{} skuMap :{}",orderSkuMap,skuMap);
        return orderSkuMap.equals(skuMap);
    }

    public List<OrderItemForeheadParam> buildData(Long orderId,List<OrderItemForeheadParam> orderItemList){
        orderItemList = orderItemList.stream()
                .map(orderItem -> {
                    orderItem.setId(RedisTools.valueOperations().increment(RedisKey.PRIMARY_KEY.ORDER_ITEM_ID));
                    orderItem.setOrderId(orderId);
                    RPCResponse<GoodsSkuDTOResultInShop> rpcSku = iGoodsSkuService.findGoodsSkuBySkuId(orderItem.getGoodsSkuId());
                    //"[1,2]"
                    String goodsSpecificationStr = rpcSku.getData().getGoodsSpecification();
                    String[] idList = StringUtils.substringBetween(goodsSpecificationStr, "[", "]").split(",");
                    List<String> list = Lists.newArrayList();
                    Arrays.stream(idList).forEach(strId -> {
                        RPCResponse<GoodsSpecificationDTOResult> goodsSpecification = iGoodsSpecificationService.findGoodsSpecificationById(Long.parseLong(strId));
                        String goodsSpecificationValue = goodsSpecification.getData().getGoodsSpecificationValue();
                        list.add(goodsSpecificationValue);
                    });
                    orderItem.setSpecificationInfo(StringUtils.join(list, ","));
                    orderItem.setPrice(rpcSku.getData().getCurrentPrice());
                    orderItem.setTotalPrice(orderItem.getPrice().multiply(new BigDecimal(orderItem.getNum())));
                    return orderItem;
                }).collect(Collectors.toList());
        return orderItemList;
    }


    /**
     * 保存订单详情
     * @param orderItemList 订单详情
     */
    public List<OrderItem> save(Long orderId,List<OrderItemForeheadParam> orderItemList){
        if(!checkPrice(orderItemList)){
            throw new GlobalException(ResultCode.SKU_PRICE_UPDATE);
        }
//        List<Long> skuIdList = Lists.newArrayList();
//        Map<Long, BigDecimal> orderSkuMap = new HashMap();
//        Map<Long, BigDecimal> skuMap = new HashMap();
//        orderItems.forEach(orderItem -> {
//            skuIdList.add(orderItem.getGoodsSkuId());
//            orderSkuMap.put(orderItem.getGoodsSkuId(),orderItem.getPrice().stripTrailingZeros());
//        });
//        RPCResponse<List<GoodsSkuDTOResultInShop>> goodsSkuListInRpc = iGoodsSkuService.findGoodsSkuListInSkuId(skuIdList);
//        List<GoodsSkuDTOResultInShop> rpcList = goodsSkuListInRpc.getData();
//        rpcList.forEach(sku->{
//            skuMap.put(sku.getId(),sku.getCurrentPrice().stripTrailingZeros());
//        });
//        log.debug("==============orderSkuMap :{} skuMap :{}",orderSkuMap,skuMap);
        //价格变化
//        if(!orderSkuMap.equals(skuMap)){
//            throw new GlobalException(ResultCode.SKU_PRICE_UPDATE);
//        }
        orderItemList = buildData(orderId, orderItemList);
        List<OrderItem> orderItems = TransformUtils.transformList(orderItemList, OrderItem.class);
//        orderItems = orderItems.stream()
//                .map(orderItem -> {
//                    orderItem.setOrderId(orderId);
//                    RPCResponse<GoodsSkuDTOResultInShop> rpcSku = iGoodsSkuService.findGoodsSkuBySkuId(orderItem.getGoodsSkuId());
//                    //"[1,2]"
//                    String goodsSpecificationStr = rpcSku.getData().getGoodsSpecification();
//                    String[] idList = StringUtils.substringBetween(goodsSpecificationStr, "[", "]").split(",");
//                    List<String> list=Lists.newArrayList();
//                    Arrays.stream(idList).forEach(strId->{
//                        RPCResponse<GoodsSpecificationDTOResult> goodsSpecification = iGoodsSpecificationService.findGoodsSpecificationById(Long.parseLong(strId));
//                        String goodsSpecificationValue = goodsSpecification.getData().getGoodsSpecificationValue();
//                        list.add(goodsSpecificationValue);
//                    });
//                    orderItem.setSpecificationInfo(StringUtils.join(list, ","));
//                    orderItem.setPrice(rpcSku.getData().getCurrentPrice());
//                    orderItem.setTotalPrice(orderItem.getPrice().multiply(new BigDecimal(orderItem.getNum())));
//                    return orderItem;
////            orderItemBusiness.save(orderItem);
//                }).collect(Collectors.toList());
        orderItemBusiness.save(orderItems);
        return orderItems;
    }


    public List<OrderItemResult> findListByOrderId(Long orderId){
        return TransformUtils.transformList(orderItemBusiness.findAllBy("orderId",orderId),OrderItemResult.class);
    }

    /**
     * 根据ids 删除orderItem
     * @param orderItemIdList list->（1,2,3）
     */
    public void deleteIds(List<Long> orderItemIdList) {
        orderItemBusiness.deleteByIds(StringUtils.join(orderItemIdList,","));
    }

    public static void main(String[] args) {
        HashMap<Long, BigDecimal> objectObjectHashMap = new HashMap<>();
        HashMap<Long, BigDecimal> objectObjectHashMap2 = new HashMap<>();
        BigDecimal bigDecimal = new BigDecimal(2.98);
        objectObjectHashMap.put(1L,bigDecimal);
        objectObjectHashMap.put(2L,bigDecimal);
        BigDecimal bigDecimal2 = new BigDecimal(2.980);
        objectObjectHashMap2.put(1L,bigDecimal2);
        objectObjectHashMap2.put(2L,bigDecimal2);
        System.out.println(objectObjectHashMap.equals(objectObjectHashMap2));
        System.out.println(bigDecimal.equals(bigDecimal2));
        int i = bigDecimal.compareTo(bigDecimal2);
        System.out.println(i);
    }



}
